package com.byxy.ssm.demo.controller;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.byxy.ssm.demo.entity.User;
import com.byxy.ssm.demo.service.UserService;

import lombok.extern.slf4j.Slf4j;

@Controller
@RequestMapping("/")
@Slf4j//lombok log.info
public class UserController {
	
	 // 1. 显示页面 
	 // 2. 定义业务类与方法
	 // 3. 定义Dao接口
	 // 4. 单元测试业务接口
	 // 5. 控制层与业务类整合
	 // 6. UI层与控制整合
	@Autowired
	private UserService userService;
	
	@GetMapping("toLoginPage.do")//登录连接
	public String login(){
		return "login";
	}
	
	@PostMapping("userLogin.do")
	public String login(@RequestParam("username") String username, @RequestParam("password") String password,
			HttpSession session, Model model) {

		// 1 创建Subject
		Subject subject = SecurityUtils.getSubject();
		// 2. 创建Token
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		try {
			// 3.登录方法
			subject.login(token);
			User user = (User) subject.getPrincipal();
			session.setAttribute("USER", user);
		} catch (UnknownAccountException e) {
			model.addAttribute("error", "用户不存在");
			return "redirect:toLoginPage.do?error=error";
		} catch (IncorrectCredentialsException e) {
			model.addAttribute("error", "密码不正确");
			return "redirect:toLoginPage.do?error=error";
		}

// 		User user=userService.login(username,password);
//		if (user==null) {
//			model.addAttribute("error","error");
//			return "redirect:toLoginPage.do?error=error";
//		}
//		session.setAttribute("USER", user);
		return "redirect:toMainPage.do";
	}
	
	@GetMapping("toSignUpPage.do")//注册连接
	public String signUp(){
		return "signUp";
	}
	
	@PostMapping("userSignUp.do")
	public String reg(@RequestParam("userName") String username, @RequestParam("userNick") String userNick,
			@RequestParam("userPassword") String password, @RequestParam("userType") Integer userType) {
		if (userService.reg(username, password, userNick, userType)) {
			return "redirect:toLoginPage.do";
		}
		return "redirect:toSignUpPage.do?error=error";
	}
	
	@GetMapping("userSignOut.do")//退出登录
	public String logout(HttpSession session) {
		session.removeAttribute("USER");
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "redirect:toLoginPage.do";
	}
	
	
	
}
